package com.kinon.norogamilk.http;

import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.kinon.norogamilk.application.MilkApp;

import io.reactivex.subscribers.ResourceSubscriber;
import retrofit2.HttpException;

/**
 * Created by lhqq on 2017-12-20.
 */

public abstract class CommonSubscriber<T> extends
        ResourceSubscriber<T> {

    private TextView mView;
    private String mErrorMsg;
    private boolean isShowErrorState = true;

    protected CommonSubscriber() {

    }

    protected CommonSubscriber(TextView view) {
        this.mView = view;
    }

    protected CommonSubscriber(TextView view, String errorMsg) {
        this.mView = view;
        this.mErrorMsg = errorMsg;
    }

    protected CommonSubscriber(TextView view,
                               boolean isShowErrorState) {
        this.mView = view;
        this.isShowErrorState = isShowErrorState;
    }

    protected CommonSubscriber(TextView view, String errorMsg,
                               boolean isShowErrorState) {
        this.mView = view;
        this.mErrorMsg = errorMsg;
        this.isShowErrorState = isShowErrorState;
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onError(Throwable t) {
//        if (mView == null) {
//            return;
//        }
        Log.e("http", "onError==" + t.getMessage());
        if (mErrorMsg != null && !TextUtils.isEmpty(mErrorMsg)) {
            Toast.makeText(MilkApp.getInstance(),
                    mErrorMsg, Toast.LENGTH_SHORT).show();
            onFail(t, 1000, mErrorMsg);
        } else if (t instanceof ApiException) {
            Toast.makeText(MilkApp.getInstance(),
                    t.getMessage(), Toast.LENGTH_SHORT).show();
            onFail(t, 1001, t.getMessage());
        } else if (t instanceof HttpException) {
            Toast.makeText(MilkApp.getInstance(),
                    "数据加载失败", Toast.LENGTH_SHORT).show();
            onFail(t, 1002, "数据加载失败");
        } else {
//            mView.setText("未知错误");
            Toast.makeText(MilkApp.getInstance(),
                    "未知错误", Toast.LENGTH_SHORT).show();
            onFail(t, 1003, "未知错误");
//            mView.showErrorMsg("未知错误");

//            LogUtil.d(e.toString());
        }
    }

    public abstract void onFail(Throwable t, int code, String msg);
}
